package com.hy.mvc.biz.utils.application;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * <pre>
 *    author  : Booker
 *    time    : 2017/12/13 17:02
 *    desc    : ApplicationConextUtil
 *    version : v1.0
 * </pre>
 */
public class ApplicationConextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * @param name
     * @return
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    /**
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        if (clazz == null) {
            return null;
        }
        return applicationContext.getBean(clazz);
    }

    /**
     * @param beanName
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        if (clazz == null) {
            return null;
        }
        if ("".equals(beanName) || null == beanName) {
            return null;
        }
        return applicationContext.getBean(beanName, clazz);
    }

    /**
     * 是否包含bean
     *
     * @param beanName
     * @return
     */
    public static boolean containsBean(String beanName) {
        return applicationContext.containsBean(beanName);
    }

    /**
     * 是否是单例
     *
     * @param beanName
     * @return
     */
    public static boolean isSingleton(String beanName) {
        return applicationContext.isSingleton(beanName);
    }

    /**
     * bean的类型
     *
     * @param beanName
     * @return
     */
    public static Class getType(String beanName) {
        return applicationContext.getType(beanName);
    }

    /**
     * 加载Spring配置文件时，如果Spring配置文件中所定义的Bean类实现了ApplicationContextAware接口，会自动调用该方法
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationConextUtil.applicationContext = applicationContext;
    }
}
